#pragma once
#include <iostream>
#include <string>
#include <memory>
#include "Socket.hpp"

using namespace socket_ns;
class SelectServer
{
    const static int N = sizeof(fd_set) * 8;
    const static int defaultfd = -1;

public:
    SelectServer(uint16_t port)
        : _port(port),
          _listensock(std::make_unique<TcpSocket>())
    {
        // 创建套接字
        InetAddr addr("0", _port);
        _listensock->BuildListenSocket(addr);

        // 初始化辅助数组
        for (int i = 0; i < N; i++)
        {
            _fd_array[i] = defaultfd;
        }
        _fd_array[0] = _listensock->SockFd();
    }
    void AcceptClient()
    {
        InetAddr clientaddr;
        int sockfd = _listensock->Accepter(&clientaddr);
        if (sockfd < 0)
            return;

        LOG(DEBUG, "Get new Link, sockfd: %d, client info %s:%d\n", sockfd, clientaddr.Ip().c_str(), clientaddr.Port());
        int pos = 1;

        // 把sockfd放入文件描述符集中
        for (; pos < N; pos++)
        {
            if (_fd_array[pos] == defaultfd)
                break;
        }

        if (pos == N)
        {
            // 没有空位置，太火热了，要断开连接
            ::close(sockfd);
            LOG(WARNING, "server is full!\n");
            return;
        }
        else
        {
            // 找到空位置
            _fd_array[pos] = sockfd;
            LOG(DEBUG, "%d add to select array!\n", sockfd);
        }
        LOG(DEBUG, "curr fd_array[] fd list : %s\n", RfdsToString().c_str());
    }

    void ServiceIO(int pos)
    {
        // 读就绪，此时读取数据不会阻塞
        char buffer[1024];
        ssize_t n = ::recv(_fd_array[pos], &buffer, sizeof(buffer) - 1, 0);

        if (n > 0) // 读取成功
        {
            buffer[n] = 0;
            // 打印读到的消息
            std::cout << "client say# " << buffer << std::endl;

            // 构建应答
            std::string echo_string = "[server echo]# ";
            echo_string += buffer;

            // 发送应答
            ::send(_fd_array[pos], echo_string.c_str(), echo_string.size(), 0);
        }
        else if (n == 0) // 读完了
        {
            LOG(DEBUG, "%d is closed\n", _fd_array[pos]);
            // 关闭文件描述符
            ::close(_fd_array[pos]);

            // 把对应的描述符从辅助数组中删除
            _fd_array[pos] = defaultfd;
            LOG(DEBUG, "curr fd_array[] fd list : %s\n", RfdsToString().c_str());
        }
        else // 读失败
        {
            LOG(DEBUG,"%d recv error\n",_fd_array[pos]);
            ::close(_fd_array[pos]);
            _fd_array[pos]=defaultfd;

            LOG(DEBUG, "curr fd_array[] fd list : %s\n", RfdsToString().c_str());

        }
    }
    std::string RfdsToString()
    {
        std::string fdstr;
        for (int i = 0; i < N; i++)
        {
            if (_fd_array[i] == defaultfd)
                continue;

            fdstr += std::to_string(_fd_array[i]);
            fdstr += " ";
        }
        return fdstr;
    }
    void HandlerEvent(fd_set &rfds)
    {
        for (int i = 0; i < N; i++)
        {
            if (_fd_array[i] == defaultfd)
                continue;
            if (FD_ISSET(_fd_array[i], &rfds)) // 读事件就绪
            {
                if (_fd_array[i] == _listensock->SockFd())
                {
                    AcceptClient();
                }
                else
                {
                    ServiceIO(i);
                }
            }
        }
    }
    void Loop()
    {
        while (true)
        {
            // 每次循环都要创建文件描述符集
            fd_set rfds;
            FD_ZERO(&rfds); // 清空
            int max_fd = defaultfd;

            // 把辅助数组中有效的文件描述符放入描述符集中
            for (int i = 0; i < N; i++)
            {
                if (_fd_array[i] == defaultfd)
                    continue;

                // 描述符有效
                FD_SET(_fd_array[i], &rfds);

                // 更新出最大的文件描述符
                if (max_fd < _fd_array[i])
                {
                    max_fd = _fd_array[i];
                }
            }

            // 等待读事件

            struct timeval timeout = {0, 0};
            int n = select(max_fd + 1, &rfds, nullptr, nullptr, nullptr);
            switch (n)
            {
            case 0:
                LOG(INFO, "timeout, %d.%d\n", timeout.tv_sec, timeout.tv_usec);
                break;
            case -1:
                LOG(ERROR, "select error...\n");
                break;
            default:
                LOG(DEBUG, "Event Happen. n: %d\n", n);
                HandlerEvent(rfds); // 处理事件
                break;
            }
        }
    }
    ~SelectServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
    int _fd_array[N]; // 辅助数组
};